﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AntUnion.FrameWork.Model.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net.Http.Headers;
using Util;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using AntUnion.FrameWork.Web.Extend;
using Newtonsoft.Json;
using AntUnion.FrameWork.Web.Service;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class BaseController : ControllerBase
    {
        #region 公用变量
        public LogService logService = new LogService();
        #endregion

        private readonly mtContext _context;

        private readonly IWebHostEnvironment _hostingEnv;
        public BaseController(mtContext context, IWebHostEnvironment env)
        {
            _context = context;
            _hostingEnv = env;
        }

        public static string BaseUrl = DefaultCache.SystemConfig()["base_url"].ToString();
        public static string PATH = "upload";

        /// <summary>
        /// 请求过滤处理
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Session.TryGetValue("User", out byte[] result);

            if (result == null)
            {
                string ip = HttpContext.Connection.RemoteIpAddress.ToString();
                string ipAddress = "";
                if (ip != "::1")
                {
                    string[] ips = ip.Split('.');
                    if (ips.Length == 4)
                    {
                        try
                        {
                            IPModel iPModel = HttpUtil.HttpGet($"http://whois.pconline.com.cn/ipJson.jsp?ip={ip}&json=true").ToObject<IPModel>();
                            ipAddress = iPModel.addr;
                        }
                        catch
                        {
                            ipAddress = "";
                        }
                    }
                }
                if (ip.Contains("::"))
                {
                    var realip = HttpContext.Request.Headers["X-Real-IP"].FirstOrDefault();
                    if (realip != null)
                    {
                        ip = realip;
                        try
                        {
                            IPModel iPModel = HttpUtil.HttpGet($"http://whois.pconline.com.cn/ipJson.jsp?ip={ip}&json=true").ToObject<IPModel>();
                            ipAddress = iPModel.addr;
                        }
                        catch
                        {
                            ipAddress = "";
                        }
                    }
                }
                string[] loginInfo = GetCookies("User").Split("|");
                if (loginInfo != null && loginInfo.Length == 2)
                {
                    string UserPwd = SecurityUtil.EncryptPwd(loginInfo[1]);
                    TbUser data = _context.TbUsers.FirstOrDefault(k => k.LoginName == loginInfo[0] && k.LoginPwd == UserPwd && k.Isdel == 0);
                    if (data != null)
                    {
                        if (data.State == 1)
                        {
                            data.LastIp = ip;
                            data.LastTime = DateTimeUtil.Now;
                            logService.AddLoginLogs(filterContext.HttpContext, data.LoginName, data.Id, 1, "loginSucceeded", ip, ipAddress, 0);
                            AdminModel model = new AdminModel
                            {
                                Id = data.Id,
                                UserName = data.UserName,
                                LoginName = data.LoginName,
                                State = data.State,
                                Pid = data.Pid,
                                UserType = 0,
                                Level = data.Level
                            };
                            SetSessions("User", model);
                            SetCookies("User", loginInfo[0] + "|" + loginInfo[1], expires * 60);
                            _context.SaveChanges();
                        }
                        else
                        {
                            logService.AddLoginLogs(filterContext.HttpContext, data.LoginName, data.Id, 0, "loginManagementSystemFailed", ip, ipAddress, 0);
                            filterContext.Result = new RedirectResult("~/Console/Login/NeedLogin");
                            return;
                        }
                    }
                    else
                    {
                        logService.AddLoginLogs(filterContext.HttpContext, loginInfo[0], 0, 0, "loginManagementSystemFailed", ip, ipAddress, 0);
                        filterContext.Result = new RedirectResult("~/Console/Login/NeedLogin");
                        return;
                    }
                }
                else
                {
                    filterContext.Result = new RedirectResult("~/Console/Login/NeedLogin");
                    return;
                }
            }
            else
            {
                logService.AddOperatorLogs(filterContext, User.LoginName, User.Id, 0);
            }
            base.OnActionExecuting(filterContext);
        }

        public new AdminModel User
        {
            get { return GetSession<AdminModel>("User"); }
        }

        #region 图片上传

        [HttpPost]
        [RequestSizeLimit(52428800)]
        public JsonResult UploadFile(int? width, int? height, int? type)
        {
            Result re = new Result();
            try
            {
                var file = Request.Form.Files[0];
                long size = file.Length;
                if (size > 52428800)
                {
                    re.Code = 1;
                    re.Msg = "上传的文件不能大于50M！";
                }
                else
                {
                    FileData data = new FileData();
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    //没有合适的格式
                    string extName = Path.GetExtension(fileName.ToString()).ToLower();
                    string src = "";
                    if (ImageFactory.GetImgFormat().ContainsKey(extName))
                    {
                        Image image = Image.FromStream(file.OpenReadStream());
                        src = ImageFactory.SaveImage(image, "upload", fileName, width, height);
                    }
                    else
                    {
                        src = ImageFactory.SaveFile(file, fileName, PATH);
                    }
                    if (type == 1)
                    {
                        src = BaseUrl + src;
                    }
                    data.Src = src;
                    re.Data = data;
                    re.Code = 0;
                    re.Msg = "上传成功";
                }
            }
            catch (Exception ex)
            {
                re.Code = -1;
                re.Msg = ex.Message;
            }
            return new JsonResult(re);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="imgpath"></param>
        /// <param name="filepath"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DelFile(string imgpath = "", string filepath = "")
        {
            Result res = new Result();
            try
            {
                if (!string.IsNullOrEmpty(imgpath))
                {
                    imgpath = imgpath.Replace(Request.GetAbsoluteUri(), "").Replace("/", "\\");
                    string filePath = $@"{_hostingEnv.WebRootPath}{imgpath}";
                    if (System.IO.File.Exists(filePath))
                        System.IO.File.Delete(filePath);
                }
                if (!string.IsNullOrEmpty(filepath))
                {
                    filepath = filepath.Replace(Request.GetAbsoluteUri(), "").Replace("/", "\\");
                    string filePath = $@"{_hostingEnv.WebRootPath}{filepath}";
                    if (System.IO.File.Exists(filePath))
                        System.IO.File.Delete(filePath);
                }
                res.Code = 0;
                res.Data = 0;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        //[HttpPost]
        //public JsonResult UploadFileAli(int towidth = 400)
        //{
        //    Result re = new Result();
        //    try
        //    {
        //        var files = Request.Form.Files;
        //        long size = files.Sum(f => f.Length);
        //        if (size > 104857600)
        //        {
        //            re.Code = 1;
        //            re.Msg = "上传的文件不能大于100M！";
        //        }
        //        else
        //        {
        //            List<FileData> filePathResultList = new List<FileData>();
        //            foreach (var file in files)
        //            {
        //                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName;
        //                string fileFolder = DateTimeHelper.UtcNow.ToString("yyyyMM");
        //                string filePath = hostingEnv.WebRootPath + $@"\UpLoad\{fileFolder}\";

        //                if (!Directory.Exists(filePath))
        //                {
        //                    Directory.CreateDirectory(filePath);
        //                }
        //                string extName = Path.GetExtension(fileName.ToString()).ToLower();
        //                string newFileName = DateTimeHelper.UtcNow.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + extName;
        //                string fileFullName = filePath + newFileName;
        //                //获取图片的返回类型
        //                var contentTypDict = new Dictionary<string, string> {
        //                        {".jpg","image/jpeg"},
        //                        {".jpeg","image/jpeg"},
        //                        {".jpe","image/jpeg"},
        //                        {".png","image/png"},
        //                        {".bmp","image/bmp"}
        //                    };
        //                if (contentTypDict.ContainsKey(extName))
        //                {
        //                    Image image = Image.FromStream(file.OpenReadStream());
        //                    //找到新尺寸
        //                    if (image.Width < towidth)
        //                        towidth = image.Width;
        //                    var toheight = image.Height * towidth / image.Width;
        //                    //新建一个bmp图片
        //                    Bitmap bitmap = new Bitmap(towidth, toheight);
        //                    //新建一个画板
        //                    Graphics g = Graphics.FromImage(bitmap);
        //                    //设置高质量插值法
        //                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        //                    //设置高质量,低速度呈现平滑程度
        //                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        //                    //清空画布并以透明背景色填充
        //                    g.Clear(Color.Transparent);
        //                    //在指定位置并且按指定大小绘制原图片的指定部分
        //                    g.DrawImage(image, new Rectangle(0, 0, towidth, toheight), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
        //                    try
        //                    {
        //                        //以jpg格式保存缩略图
        //                        switch (extName.ToLower())
        //                        {
        //                            case ".gif":
        //                                bitmap.Save(fileFullName, System.Drawing.Imaging.ImageFormat.Gif);
        //                                break;
        //                            case ".jpg":
        //                                bitmap.Save(fileFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
        //                                break;
        //                            case ".bmp":
        //                                bitmap.Save(fileFullName, System.Drawing.Imaging.ImageFormat.Bmp);
        //                                break;
        //                            case ".png":
        //                                bitmap.Save(fileFullName, System.Drawing.Imaging.ImageFormat.Png);
        //                                break;
        //                            default:
        //                                bitmap.Save(fileFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
        //                                break;
        //                        }
        //                        FileData data = new FileData
        //                        {
        //                            Src = CommonHelper.UploadAliyunImg(newFileName, fileFullName),// $"/UpLoad/{fileFolder}/{newFileName}";                                
        //                            Width = towidth,
        //                            Height = toheight
        //                        };
        //                        filePathResultList.Add(data);
        //                    }
        //                    finally
        //                    {
        //                        image.Dispose();
        //                        bitmap.Dispose();
        //                        g.Dispose();
        //                    }
        //                }
        //                else
        //                {
        //                    using (FileStream fs = System.IO.File.Create(fileFullName))
        //                    {
        //                        file.CopyTo(fs);
        //                        fs.Flush();
        //                    }
        //                    FileData data = new FileData();
        //                    data.Src = $"/UpLoad/{fileFolder}/{newFileName}";
        //                    filePathResultList.Add(data);
        //                }
        //            }
        //            re.Data = filePathResultList;
        //            re.Code = 0;
        //            re.Msg = "上传成功";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        re.Code = -1;
        //        re.Msg = ex.Message;
        //    }
        //    return new JsonResult(re);
        //}


        //[HttpPost]
        //public JsonResult UploadFileApp()
        //{
        //    Result re = new Result();
        //    try
        //    {
        //        var files = Request.Form.Files;
        //        long size = files.Sum(f => f.Length);
        //        if (size > 104857600)
        //        {
        //            re.Code = 1;
        //            re.Msg = "上传的文件不能大于100M！";
        //        }
        //        else
        //        {
        //            List<FileData> filePathResultList = new List<FileData>();
        //            foreach (var file in files)
        //            {
        //                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName;
        //                string fileFolder = DateTimeHelper.UtcNow.ToString("yyyyMM");
        //                string filePath = hostingEnv.WebRootPath + $@"\UpLoad\{fileFolder}\";

        //                if (!Directory.Exists(filePath))
        //                {
        //                    Directory.CreateDirectory(filePath);
        //                }
        //                string extName = Path.GetExtension(fileName.ToString()).ToLower();
        //                string newFileName = DateTimeHelper.UtcNow.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + extName;
        //                string fileFullName = filePath + newFileName;
        //                //获取图片的返回类型
        //                var contentTypDict = new Dictionary<string, string> {
        //                        {".jpg","image/jpeg"},
        //                        {".jpeg","image/jpeg"},
        //                        {".jpe","image/jpeg"},
        //                        {".png","image/png"},
        //                        {".bmp","image/bmp"}
        //                    };
        //                if (contentTypDict.ContainsKey(extName))
        //                {
        //                    Image image = Image.FromStream(file.OpenReadStream());

        //                    using (FileStream fs = System.IO.File.Create(fileFullName))
        //                    {
        //                        file.CopyTo(fs);
        //                        fs.Flush();
        //                    }

        //                    FileData data = new FileData();
        //                    data.Src = CommonHelper.UploadAliyunImg(newFileName, fileFullName);// $"/UpLoad/{fileFolder}/{newFileName}";                                
        //                    data.Width = image.Width;
        //                    data.Height = image.Height;
        //                    filePathResultList.Add(data);
        //                }
        //                else
        //                {
        //                    using (FileStream fs = System.IO.File.Create(fileFullName))
        //                    {
        //                        file.CopyTo(fs);
        //                        fs.Flush();
        //                    }
        //                    FileData data = new FileData();
        //                    data.Src = $"/UpLoad/{fileFolder}/{newFileName}";
        //                    filePathResultList.Add(data);
        //                }
        //            }
        //            re.Data = filePathResultList;
        //            re.Code = 0;
        //            re.Msg = "上传成功";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        re.Code = -1;
        //        re.Msg = ex.Message;
        //    }
        //    return new JsonResult(re);
        //}
        #endregion

        public void AddLog(string cont)
        {
            TbLog log = new TbLog
            {
                Cont = cont,
                Operator = User.Id,
                Name = User.LoginName,
                Source = User.UserType,
                Addtime = DateTimeUtil.Now
            };
            _context.TbLogs.Add(log);
        }

        /// <summary>
        /// 后台用户过虑器
        /// </summary>
        /// <returns></returns>
        public IQueryable<TbUser> UserFilter()
        {
            var user = _context.TbUsers.AsNoTracking().Where(k => true);
            if (User.Level == 2)
            {
                user = user.Where(k => (k.Id == User.Id || k.Pid == User.Id) && k.Isdel == 0);
            }
            else if (User.Level == 3)
            {
                user = user.Where(k => k.Id == User.Id && k.Isdel == 0);
            }
            return user;
        }
    }
}